package com.xique.door.device.freeview.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.log.annotation.Log;
import com.xique.common.log.enums.BusinessType;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.dto.CommandDto;
import com.xique.door.bean.request.wxMessage.WxDoorOpenMessageSendRequest;
import com.xique.door.biz.service.IWxMessageSendBizService;
import com.xique.door.device.freeview.bean.request.advertisement.UpdatePlayPolicyGetStateRequest;
import com.xique.door.device.freeview.bean.request.card.ConfirmCardsSyncedRequest;
import com.xique.door.device.freeview.bean.request.card.GetCardsInfoRequest;
import com.xique.door.device.freeview.bean.request.face.ConfirmFaceRecognitionsSyncedRequest;
import com.xique.door.device.freeview.bean.request.face.FaceRecognitionsInfoRequest;
import com.xique.door.device.freeview.bean.request.record.OssFileDetail;
import com.xique.door.device.freeview.bean.request.record.ReportAccessRecordDetailRequest;
import com.xique.door.device.freeview.bean.request.record.ReportAccessRecordRequest;
import com.xique.door.device.freeview.bean.request.record.ReportAlarmRecordRequest;
import com.xique.door.device.freeview.bean.vo.device.DeviceConfigServerExtrasVo;
import com.xique.door.device.freeview.bean.vo.device.DeviceConfigServerVo;
import com.xique.door.device.freeview.bean.vo.device.DeviceConfigVo;
import com.xique.door.device.freeview.bean.vo.face.FaceRecognitionsVo;
import com.xique.door.device.freeview.cache.InterfaceListCache;
import com.xique.door.device.freeview.constant.FreeViewConstant;
import com.xique.door.device.freeview.service.biz.FreeviewBizService;
import com.xique.door.device.freeview.util.FreeviewRedisUtil;
import com.xique.door.service.*;
import com.xique.door.util.RedisUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: caogangquan
 * @Date: 2021/10/13 15:30
 * @Description:
 */
@Controller
@RequestMapping("/engine-master/api")
@Slf4j
public class FreeviewApiController {

    @Value("${alioss.endpoint}")
    private String endPoint;

    @Value("${alioss.accessKeyId}")
    private String accessKeyId;

    @Value("${alioss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${alioss.park.bucketName}")
    private String parkBucketName;

    @Value("${alioss.park.filehost}")
    private String fileHost;


    @Value("${freeview.mqtt_server_ip}")
    private String mqttServerIp;

    @Value("${freeview.mqtt_port}")
    private Integer mqttPort;

    @Value("${freeview.plaform_server_ip}")
    private String plaformServerIp;

    @Value("${freeview.platform_port}")
    private Integer platformPort;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private FreeviewBizService freeviewBizService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Autowired
    private IVerifyRecordsService verifyRecordsService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IDCardService cardService;

    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private IBuildBuildingService buildBuildingService;

    @Autowired
    private IBuildingDeviceService buildingDeviceService;

    @Autowired
    private IDCardDeviceService cardDeviceService;

    @Autowired
    private IUserDeviceService userDeviceService;

    @Autowired
    private FreeviewRedisUtil freeviewRedisUtil;

    @Autowired
    private IWxMessageSendBizService wxMessageTemplateBizService;

    //------------------------------------------------设备接入-------------------------------------------------

    @GetMapping("/getCurrentUTCTimeStamp")
    @ResponseBody
    @ApiOperation("设备向平台获取时间戳")
    public Object getCurrentUTCTimeStamp() {
        //设备需要不带时区的时间，设备会以设备所在时区做时间计算
        Map<String, String> map = Collections.singletonMap("timestamp", String.valueOf(DateUtils.getCurrentUTCTimestamp()));
        return map;
    }

    @GetMapping("/deviceAccesstoken")
    @ResponseBody
    @ApiOperation("设备向平台申请访问令牌")
    public Object getDeviceAccesstoken(HttpServletRequest request) {
        Map<String, Object> returnMap = new HashMap<>();
        String username = request.getParameter("username");
        String[] split = username.split("@");
        String tokenType = request.getParameter("tokenType");
        String devSn = "";
        if ("1".equals(tokenType)) {
            //tokenType为1时，username：tenantCode@小区编号_deviceNumber
            String deviceNumber = split[1].substring(split[1].indexOf("_", 0) + 1);
            //平台添加全视通设备时默认设备编号等于devsn
            AccessDevice accessDevice = new AccessDevice();
            accessDevice.setDeviceNumber(deviceNumber);
            List<AccessDevice> deviceList = accessDeviceService.selectAccessDeviceList(accessDevice);
            if (deviceList.isEmpty()) {
                return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.UNAUTHORIZED);
            }
            devSn = deviceList.get(0).getDevSn();
        } else {
            //tokenType为1时，username：aid@cid devSn == cid
            devSn = split[1];
        }
        if (StringUtils.isEmpty(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.UNAUTHORIZED);
        }
        String uuid = UUID.randomUUID().toString();
        String token = FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + uuid;
        //设置七天的过期时间，每次都重置更新时间
        redisUtil.set(token, devSn, 7 * 24 * 60 * 60);
        returnMap.put("token", uuid);
        returnMap.put("expiredTime", 7200);
        return returnMap;
    }


    @GetMapping("/getInterfaceList")
    @ResponseBody
    @ApiOperation("设备向平台获取接口清单")
    public Object getInterfaceList(HttpServletRequest request) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + request.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return InterfaceListCache.interfaceMap;
    }

    @GetMapping("/getDeviceConfig")
    @ResponseBody
    @ApiOperation("DS001-获取配置信息")
    public Object getDeviceConfig(HttpServletRequest request) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + request.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        DeviceConfigVo deviceConfigVo = new DeviceConfigVo();
        //无用字段
        deviceConfigVo.setAppID("0002");
        List<DeviceConfigServerVo> serverList = new ArrayList<>();
        deviceConfigVo.setServerList(serverList);
        DeviceConfigServerVo serverVo = new DeviceConfigServerVo();
        //1代表mqtt服务器
        serverVo.setServerType(1);
        serverVo.setIp(mqttServerIp);
        serverVo.setPort(mqttPort);
        serverVo.setServerUsername(String.valueOf(devSn));
        //设备有必填校验，随便给个值
        serverVo.setServerPassword("1");
        DeviceConfigServerExtrasVo extrasVo = new DeviceConfigServerExtrasVo();
        //0的时候可以保留 session
        extrasVo.setCleanSession(false);
        extrasVo.setCommunicationTimeout(2000);
        extrasVo.setKeepalive(300);
        extrasVo.setStandbyServerIP("");
//        extrasVo.setSimpleMqttUsername("xique");
//        extrasVo.setSimpleMqttPassword("1DeJHG6IOZBQVF5y");
        extrasVo.setSimpleMqttUsername("");
        extrasVo.setSimpleMqttPassword("");
        extrasVo.setTls(false);
        extrasVo.setObjectRootPath("");
        extrasVo.setBucketName("");
        serverVo.setExtras(extrasVo);
        serverList.add(serverVo);

        DeviceConfigServerVo serverVo2 = new DeviceConfigServerVo();
        serverVo2.setServerType(0);
        serverVo2.setIp(plaformServerIp);
        serverVo2.setPort(platformPort);
        //设备有必填校验，随便给个值
        serverVo2.setServerUsername(String.valueOf(devSn));
        //设备有必填校验，随便给个值
        serverVo2.setServerPassword("1");
        DeviceConfigServerExtrasVo extrasVo2 = new DeviceConfigServerExtrasVo();
        //0的时候可以保留 session
        extrasVo2.setCleanSession(false);
        extrasVo2.setCommunicationTimeout(2000);
        extrasVo2.setKeepalive(300);
        extrasVo2.setStandbyServerIP("");
        extrasVo2.setTls(false);
        extrasVo2.setStandbyServerIP("");
        extrasVo2.setObjectRootPath("");
        extrasVo2.setBucketName("");
        extrasVo2.setSimpleMqttUsername("");
        extrasVo2.setSimpleMqttPassword("");
        serverVo2.setExtras(extrasVo2);
        serverList.add(serverVo2);


        DeviceConfigServerVo serverVo3 = new DeviceConfigServerVo();
        serverVo3.setServerType(21);
        serverVo3.setIp(endPoint);
        serverVo3.setPort(1);
        serverVo3.setServerUsername(accessKeyId);
        serverVo3.setServerPassword(accessKeySecret);
        DeviceConfigServerExtrasVo extrasVo3 = new DeviceConfigServerExtrasVo();
        //0的时候可以保留 session
        extrasVo3.setCleanSession(false);
        extrasVo3.setCommunicationTimeout(2000);
        extrasVo3.setKeepalive(300);
        extrasVo3.setTls(false);
        extrasVo3.setBucketName(parkBucketName);
        extrasVo3.setObjectRootPath(fileHost);
        extrasVo3.setStandbyServerIP("");
        extrasVo3.setSimpleMqttUsername("");
        extrasVo3.setSimpleMqttPassword("");
        serverVo3.setExtras(extrasVo3);
        serverList.add(serverVo3);
        return deviceConfigVo;
    }

    //------------------------------------------------人脸信息-------------------------------------------------

    @GetMapping("/getFaceRecognitions")
    @ResponseBody
    @ApiOperation("DO006-获取单个人脸同步数据")
    public Object getFaceRecognitions(@RequestParam("eventID") String eventId, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("----------DO006获取单个人脸同步数据-----------" + new Date() + "eventID" + eventId);
        FaceRecognitionsVo faceRecognitions = freeviewBizService.getFaceRecognitions(eventId);
        log.info(faceRecognitions.toString());
        return faceRecognitions;
    }


    @PostMapping("/getFaceRecognitionsInfo")
    @ResponseBody
    @ApiOperation("DS006-获取指定人脸的详细信息")
    public Object getFaceRecognitionsInfo(@RequestBody FaceRecognitionsInfoRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("----------DS006获取指定人脸的详细信息-----------" + new Date() + "eventID" + request.getEventID());
        Map<String, Object> faceRecognitionsInfo = freeviewBizService.getFaceRecognitionsInfo(request);
        log.info("人脸下发参数： " + faceRecognitionsInfo.toString());
        return faceRecognitionsInfo;
    }


    @PostMapping("/confirmFaceRecognitionsSynced")
    @ResponseBody
    @ApiOperation("DO008-确认同步单个人脸")
    public Object confirmFaceRecognitionsSynced(@RequestBody ConfirmFaceRecognitionsSyncedRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("----------DO008人脸同步成功-----------" + new Date() + "eventID" + request.getEventId());
        log.info("确认同步单个人脸,时间:{},eventID:{},参数:{}，设备:{}", new Date(), request.getEventId(), request, devSn);
        return freeviewBizService.confirmFaceRecognitionsSynced(request, String.valueOf(devSn));
    }

    //------------------------------------------------广告管理-------------------------------------------------
    @GetMapping("/getAdvertisements")
    @ResponseBody
    @ApiOperation("DS010-获取广告公告")
    public Object getAdvertisements(@RequestParam("eventID") String eventId, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("----------DS010-获取广告公告-----------" + new Date() + "eventID" + eventId);
        return freeviewBizService.getAdvertisements(eventId);
    }


    @PostMapping("/updatePlayPolicyGetState")
    @ResponseBody
    @ApiOperation("DS011-广告公告更新/清空的结果上报")
    public Object updatePlayPolicyGetState(@RequestBody UpdatePlayPolicyGetStateRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("----------DS011-广告公告更新/清空的结果上报-----------" + new Date() + "eventID" + request.getEventID());
        log.info("广告公告： " + JSONObject.toJSONString(request));
        //TODO修改下发状态
        return freeviewBizService.updatePlayPolicyGetState(request, String.valueOf(devSn));
    }

    //------------------------------------------------卡管理-------------------------------------------------
    @GetMapping("/getCards")
    @ResponseBody
    @ApiOperation("DO001-获取单个卡同步数据")
    public Object getCards(@RequestParam("eventID") String eventId, @RequestParam(value = "requestCount", required = false) Integer requestCount, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return freeviewBizService.getCards(eventId);
    }


    @PostMapping("/getCardsInfo")
    @ResponseBody
    @ApiOperation("DS004-获取指定门禁卡的详细信息")
    public Object getCardsInfo(@RequestBody GetCardsInfoRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (StringUtils.isEmpty(request.getEventId())) {
            return null;
        }
        Object cardsInfo = freeviewBizService.getCardsInfo(request);
        log.info("DS004-获取指定门禁卡的详细信息:" + JSONObject.toJSONString(cardsInfo));
        return cardsInfo;
    }


    @PostMapping("/confirmCardsSynced")
    @ResponseBody
    @ApiOperation("DO003-单个卡同步确认")
    public Object confirmCardsSynced(@RequestBody ConfirmCardsSyncedRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (StringUtils.isEmpty(request.getEventId())) {
            return null;
        }
        log.info("---------确认卡同步请求消息" + request.toString() + "---------");
        return freeviewBizService.confirmCardsSynced(request, String.valueOf(devSn));
//        return true;
    }


    //------------------------------------------------密码管理-------------------------------------------------
    @GetMapping("/verifyPassword")
    @ResponseBody
    @ApiOperation("DS016-验证临时密码")
    public Object verifyPassword(@RequestParam("eventID") String eventId, @RequestParam(value = "password") String password, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return freeviewBizService.verifyPassword(eventId, password, devSn.toString());
    }


    //------------------------------------------------记录管理-------------------------------------------------

    @PostMapping("/reportAccessRecord")
    @ResponseBody
    @ApiOperation("DS012-上报门禁记录")
    public Object reportAccessRecord(@RequestBody ReportAccessRecordRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("门禁通行记录:," + request);
        List<ReportAccessRecordDetailRequest> accessRecords = request.getAccessRecords();
        if (accessRecords.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("msg", "门禁记录为空");
            return jsonObject;
        }
        //查询设备是哪个小区的
        AccessDevice accessDevice = new AccessDevice();
        accessDevice.setDevSn(String.valueOf(devSn));
        List<AccessDevice> deviceList = accessDeviceService.selectAccessDeviceList(accessDevice);
        log.info("门禁通行记录:设备信息：{}",deviceList);

        ReportAccessRecordDetailRequest detail = accessRecords.get(0);
        if (CollectionUtils.isEmpty(detail.getOssFileInfo())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("msg", "设备没有抓拍图片");
            return jsonObject;
        }
        OssFileDetail ossFileInfo = detail.getOssFileInfo().get(0);

        User user = new User();
        user.setCustomId(detail.getOperator());
        List<User> users = userService.selectUserList(user);
        log.info("门禁通行记录:用户信息：{}",users);

        List<Visitor> visitors = new ArrayList<>();
        if (!"0".equals(detail.getOperator())) {
            Visitor visitor = new Visitor();
            visitor.setCustomId(detail.getOperator());
            visitors = visitorService.selectVisitorList(visitor);
        }
        log.info("门禁通行记录:访客信息：{}",visitors);

        List<DCard> cards = new ArrayList<>();
        if (!"0".equals(detail.getOperator())) {
            DCard card = new DCard();
            card.setCardSn(detail.getOperator());
            cards = cardService.selectDCardList(card);
        }
        log.info("门禁通行记录:卡片信息：{}",cards);
        if (users.isEmpty() && visitors.isEmpty() && cards.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("msg", "未找到对应信息");
            return jsonObject;
        }

        VerifyRecords verifyRecords = new VerifyRecords();
        //1表示系统录入用户
        verifyRecords.setUserType("1");
        verifyRecords.setCustomId(detail.getOperator());
        verifyRecords.setPersonId("");
        verifyRecords.setVerifyStatus(detail.getAccessResult() ? "1" : "24");
        verifyRecords.setPersonType("");
        verifyRecords.setIdentifyTime(new Date(detail.getAccessTime() * 1000L));
        verifyRecords.setFaceSluiceId(String.valueOf(devSn));
        verifyRecords.setFaceSluiceName(deviceList.get(0).getName());
        verifyRecords.setPic(ossFileInfo.getUrl());
        verifyRecords.setDirection("1".equals(detail.getAccessDirection()) ? "entr" : "exit");
        if (detail.getOpenType() == 3006) {
            //刷脸
            verifyRecords.setOtype("1");
        } else if (detail.getOpenType() == 3000) {
            //刷卡
            verifyRecords.setOtype("21");
            verifyRecords.setCardSn(cards.get(0).getCardSn());
        }
        verifyRecords.setTemperature("无");
        verifyRecords.setTemperatureAlarm("0");
        if (!users.isEmpty()) {
            log.info("【微信公众号推送】用户信息：{}", users.get(0));
            verifyRecords.setUserId(users.get(0).getId());
            verifyRecords.setPersonName(users.get(0).getUserName());
            // TODO 微信公众号推送
            WxDoorOpenMessageSendRequest sendRequest = new WxDoorOpenMessageSendRequest();
            sendRequest.setUserId(verifyRecords.getUserId());
            sendRequest.setIdentityTime(verifyRecords.getIdentifyTime());
            sendRequest.setDeviceName(deviceList.get(0).getName());
            log.info("【微信公众号推送】推送请求参数：{}", sendRequest);
            wxMessageTemplateBizService.sendDoorOpenMessage(sendRequest);
        }
        if (!visitors.isEmpty()) {
            //访客刷脸
            verifyRecords.setUserId(visitors.get(0).getUserId());
            verifyRecords.setVisitorId(visitors.get(0).getId());
            verifyRecords.setPersonName(visitors.get(0).getVisitorName());
        }

        if (!CollectionUtils.isEmpty(deviceList)) {
            verifyRecords.setParkId(deviceList.get(0).getParkId());
            verifyRecords.setDeviceType(deviceList.get(0).getModel());
        } else {
            verifyRecords.setParkId(-1L);
        }
        //记录到人脸识别记录表里 VerifyRecords
        verifyRecords.setRemark("全视通上报");
        verifyRecordsService.insertVerifyRecords(verifyRecords);
        log.info("门禁通行记录结果:," + verifyRecords);
        return true;
    }

    @PostMapping("/reportAlarmRecord")
    @ResponseBody
    @ApiOperation("DS013-上报报警记录")
    public Object reportAlarmRecord(@RequestBody ReportAlarmRecordRequest request, HttpServletRequest httpServletRequest) {
        Object devSn = redisUtil.get(FreeViewConstant.REDIS_KEY_PLATFORM_TOKEN + httpServletRequest.getHeader("Authorization"));
        if (Objects.isNull(devSn)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        log.info("报警记录:," + request.toString());
        return true;
    }


    @Log(title = "全视通设备固件升级", businessType = BusinessType.UPDATE)
    @PostMapping("/upgrade")
    @ResponseBody
    @ApiOperation("全视通设备固件升级")
    public AjaxResult freeviewUpgrade(@RequestParam(value = "devSn") String devSn,
                                      @RequestParam(value = "file") MultipartFile file) {
        AccessDevice accessDevice = new AccessDevice();
        accessDevice.setDevSn(devSn);
        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceList(accessDevice);
        if (accessDeviceList.isEmpty() || !"freeview".equals(accessDeviceList.get(0).getModel())) {
            return AjaxResult.error("请选择全视通设备进行升级！");
        }
        return freeviewBizService.freeviewUpgrade(devSn, file);
    }

    @GetMapping("/insertBuildingDevice")
    @ApiOperation("楼栋设备处理")
    public Object insertBuildingDevice() {
        //1、查询所有卡
        List<AccessDevice> accessDevices = accessDeviceService.selectAccessDeviceList(new AccessDevice());
        BuildBuilding buildBuilding = new BuildBuilding();
        List<BuildBuilding> buildBuildings = buildBuildingService.selectBuildBuildingList(buildBuilding);
        List<BuildingDevice> buildingDevices = new ArrayList<>();
        for (BuildBuilding building : buildBuildings) {
            Long areaId = building.getAreaId();
            Long parkId = building.getParkId();
            List<AccessDevice> accessDeviceList = accessDevices.stream().
                    filter(e -> (e.getAccessType().equals("gate") && e.getForeignId().equals(areaId))
                            || (e.getAccessType().equals("park") && e.getForeignId().equals(parkId))
                            || (e.getAccessType().equals("cell") && e.getForeignId().equals(building.getId()))).collect(Collectors.toList());

            accessDeviceList.forEach(accessDevice -> {
                BuildingDevice buildingDevice = new BuildingDevice();
                buildingDevice.setBuildingId(building.getId());
                buildingDevice.setDeviceId(accessDevice.getId());
                buildingDevice.setCreateBy("1");
                buildingDevice.setUpdateBy("1");
                buildingDevice.setParkId(parkId);
                buildingDevices.add(buildingDevice);
            });
        }
        int i = buildingDeviceService.insertBuildingDevices(buildingDevices);
        return i;
    }

    @GetMapping("/insertCardDevice")
    @ApiOperation("卡片设备处理")
    public AjaxResult insertCardDevice() {
        List<CardUserDevice> cardUserDevices = userDeviceService.selectCardUserDeviceList();
        List<CardDevice> cardDevices = new ArrayList<>();
        List<String> keys = cardUserDevices.stream().map(e -> FreeViewConstant.REDIS_FACE_REC_STATUS_PREFIX + e.getDevSn() + ":" + "User" + ":" + e.getCustomId()).collect(Collectors.toList());
        Object batchCustomIdStatus = freeviewRedisUtil.getBatchCustomIdStatus(keys);
        List<CommandDto> commandDtos = JSON.parseArray(batchCustomIdStatus.toString(), CommandDto.class);
        for (int i = 0; i < cardUserDevices.size(); i++) {
            CardUserDevice cardUserDevice = cardUserDevices.get(i);
            CardDevice cardDevice = new CardDevice();
            cardDevice.setParkId(cardUserDevice.getParkId());
            cardDevice.setCardId(cardUserDevice.getCardId());
            cardDevice.setCardSn(cardUserDevice.getCardSn());
            cardDevice.setCustomId(cardUserDevice.getCustomId());
            cardDevice.setDeviceId(cardUserDevice.getDeviceId());
            cardDevice.setDevSn(cardUserDevice.getDevSn());
            CommandDto commandDto = commandDtos.get(i);
            if (commandDto != null) {
                cardDevice.setStatus(commandDto.getStatus());
            }
            cardDevice.setModel(cardUserDevice.getModel());
            cardDevice.setCreateBy("1");
            cardDevice.setUpdateBy("1");
            cardDevices.add(cardDevice);
        }
        int i = cardDeviceService.batchInsertCardDevices(cardDevices);
        return AjaxResult.success();
    }

    @GetMapping("/updateUserDeviceStatus")
    @ApiOperation("修改用户设备的下发状态")
    public AjaxResult updateCardDevice() {
        List<UserDevice> userDevices = userDeviceService.selectUserDeviceList(new UserDevice());
        List<String> keys = userDevices.stream().map(e -> FreeViewConstant.REDIS_FACE_REC_STATUS_PREFIX + e.getDevSn() + ":" + "User" + ":" + e.getCustomId()).collect(Collectors.toList());
        Object batchCustomIdStatus = freeviewRedisUtil.getBatchCustomIdStatus(keys);
        List<CommandDto> commandDtos = JSON.parseArray(batchCustomIdStatus.toString(), CommandDto.class);
        List<UserDevice> needUserDevices = new ArrayList<>();
        for (int i = 0; i < userDevices.size(); i++) {
            UserDevice userDevice = userDevices.get(i);
            CommandDto commandDto = commandDtos.get(i);
            if (commandDto != null) {
                userDevice.setStatus(commandDto.getStatus());
                userDevice.setUpdateTime(new Date());
                needUserDevices.add(userDevice);
            }
        }
         userDeviceService.batchUpdateUserDevice(needUserDevices);
        return AjaxResult.success();
    }
}
